package com.sky.service.impl;

import com.sky.dto.GoodsSalesDTO;
import com.sky.entity.Orders;
import com.sky.mapper.OrderMapper;
import com.sky.mapper.UserMapper;
import com.sky.service.ReportService;
import com.sky.service.WorkspaceService;
import com.sky.vo.*;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.function.BinaryOperator;
import java.util.stream.Collectors;

@Slf4j
@Service
public class ReportServiceImpl implements ReportService {

    @Autowired
    private OrderMapper orderMapper;

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private WorkspaceService workspaceService;

    /**
     * 营业额统计
     *
     * @param begin
     * @param end
     * @return
     */
    @Override
    public TurnoverReportVO turnoverStatistics(LocalDate begin, LocalDate end) {
        //构造日期列表数据，dateList  例如：2022-10-01,2022-10-02,2022-10-03
        /*List<LocalDate> dateList = new ArrayList<>();
        dateList.add(begin);
        //使用while循环，往dateList添加日期
        while (!begin.equals(end)) {
            begin = begin.plusDays(1);  //12-01,12-02...12-05,12-06
            dateList.add(begin);
        }
        log.info("dateList:{}", dateList);*/
        //抽取了公共方法，调用方法构造日期列表数据
        List<LocalDate> dateList = getDateList(begin, end);

        //构造营业额列表数据，turnoverList  例如：406.0,1520.0,75.0
        List<Double> turnoverList = new ArrayList<>();
        //统计已完成状态的订单金额amount
        //select sum(amount) from orders where status = 5 and order_time between '2023-12-06 00:00:00' and '2023-12-06 23:59:59';
        for (LocalDate date : dateList) {
            Map map = new HashMap<>();
            map.put("status", Orders.COMPLETED);
            map.put("begin", LocalDateTime.of(date, LocalTime.MIN));//2023-12-06 00:00:00
            map.put("end", LocalDateTime.of(date, LocalTime.MAX));//2023-12-06 23:59:59

            Double amountSum = orderMapper.sumByMap(map);
            //处理营业额为空的情况，使用三元运算符
            amountSum = amountSum == null ? 0.0 : amountSum;

            turnoverList.add(amountSum);
        }

        //构造vo对象并返回
        log.info("dateList.toString()={}", dateList.toString());
        log.info("turnoverList.toString()={}", turnoverList.toString());

        return TurnoverReportVO.builder()
                .dateList(StringUtils.join(dateList, ','))  //"2023-11-30,2023-12-01....2023-12-06",此方法用于字符串拼接
                .turnoverList(turnoverList.toString())
                .build();
    }

    /**
     * 用户统计
     *
     * @param begin
     * @param end
     * @return
     */
    @Override
    public UserReportVO userStatistics(LocalDate begin, LocalDate end) {
        //1，构造日期列表数据dateList-->因为跟上面方法中这步的代码相同，所以抽取出来，抽取快捷键Ctrl+Alt+M
        List<LocalDate> dateList = getDateList(begin, end);

        /*//2,构造用户总量列表数据totalUserList
        List<Integer> totalUserList = new ArrayList<>();
        //用户数据从哪里来?查询user列表   查询用户，使用到user列表，注入UserMapper
        //select count(*) from user where create_time<='2023-12-07 23:59:59';总量
        //select count(*) from user where create_time<='2023-12-07 23:59:59' and create_time>='2023-12-07 00:00:00'; 新增
        //需要统计每一天的，使用循环遍历
        for (LocalDate date : dateList) {
            //date是LocalDate类型，转换成LocalDateTime型
            LocalDateTime beginTime = LocalDateTime.of(date, LocalTime.MIN);//2023-12-07 00:00:00 一天中的最小时间
            LocalDateTime endTime = LocalDateTime.of(date, LocalTime.MAX);//2023-12-07 23:59:59  一天中的最大时间
            Integer totalUser = userMapper.countBy1(null, endTime);
            //把循环统计的每一天的数据，添加到集合中
            totalUserList.add(totalUser);
        }

        //3，构造新增用户列表数据newUserList
        List<Integer> newUserList = new ArrayList<>();
        //需要统计每一天的，使用循环遍历
        for (LocalDate date : dateList) {
            //date是LocalDate类型，转换成LocalDateTime型
            LocalDateTime beginTime = LocalDateTime.of(date, LocalTime.MIN);//2023-12-07 00:00:00 一天中的最小时间
            LocalDateTime endTime = LocalDateTime.of(date, LocalTime.MAX);//2023-12-07 23:59:59  一天中的最大时间
            Integer newUser = userMapper.countBy2(beginTime, endTime);
            //把循环统计的每一天的数据，添加到集合中
            newUserList.add(newUser);
        }*/

        //使用了通用的SQL语句，两个方法都相同，可以合并
        //2,构造用户总量列表数据totalUserList
        List<Integer> totalUserList = new ArrayList<>();
        //3，构造新增用户列表数据newUserList
        List<Integer> newUserList = new ArrayList<>();
        //需要统计每一天的，使用循环遍历
        for (LocalDate date : dateList) {
            //date是LocalDate类型，转换成LocalDateTime型
            LocalDateTime beginTime = LocalDateTime.of(date, LocalTime.MIN);//2023-12-07 00:00:00 一天中的最小时间
            LocalDateTime endTime = LocalDateTime.of(date, LocalTime.MAX);//2023-12-07 23:59:59  一天中的最大时间
            Integer totalUser = userMapper.countBy(null, endTime);
            Integer newUser = userMapper.countBy(beginTime, endTime);
            //把循环统计的每一天的数据，添加到集合中
            totalUserList.add(totalUser);
            newUserList.add(newUser);
        }


        //封装UserReportVO对象，并返回
        return UserReportVO.builder()
                .dateList(StringUtils.join(dateList, ','))
                .newUserList(StringUtils.join(newUserList, ','))
                .totalUserList(StringUtils.join(totalUserList, ','))
                .build();
        //在本方法中dateList，newUserList，totalUserList都是对象
        //在UserReportVO类中，dateList，newUserList，totalUserList是类中的属性，
        //把对象转换为另一个对象的属性的值，使用StringUtils.join()方法
        //封装对象，就是为对象赋值，用链式性赋值，使用builder()方法。
    }

    /**
     * 订单统计
     *
     * @param begin
     * @param end
     * @return
     */
    @Override
    public OrderReportVO orderStatistics(LocalDate begin, LocalDate end) {
        //1，构造日期列表数据 dateList
        List<LocalDate> dateList = getDateList(begin, end);

        //2，构造每日订单总数列表  orderCountList
        List<Integer> orderCuntList = new ArrayList<>();
        //3，构造每日有效订单数列表 validOrderCountList
        List<Integer> validOrderCountList = new ArrayList<>();

        //初始化订单总数 ，有效订单总数
        Integer totalOrderCountSum = 0;
        Integer validOrderCountSum = 0;

        //select count(*) from orders where order_time >='2023-12-07 00:00:00' and order_time <='2023-12-07 23:59:59';
        //select count(*) from orders where order_time >='2023-12-07 00:00:00' and order_time <='2023-12-07 23:59:59'and status=5;
        for (LocalDate date : dateList) {
            //遍历日期列表，并获取每一天的最小时间和最大时间
            LocalDateTime beginTime = LocalDateTime.of(date, LocalTime.MIN);
            LocalDateTime endTime = LocalDateTime.of(date, LocalTime.MAX);
            //把时间传入方法中，按时间范围查询一天的订单数量
            Integer orderCount = orderMapper.countBy(null, beginTime, endTime);
            //把查询到的每一天的订单数量，添加到订单总数列表
            orderCuntList.add(orderCount);
            //查询到的每一天的有效订单数量，添加到有效订单数列表
            Integer validOrderCount = orderMapper.countBy(Orders.COMPLETED, beginTime, endTime);
            validOrderCountList.add(validOrderCount);

            //4,统计订单总数  totalOrderCount
            totalOrderCountSum += orderCount;

            //5,统计有效订单总数  validOrderCount
            validOrderCountSum += validOrderCount;


        }
        log.info("订单总数列表={}", orderCuntList);
        log.info("有效订单总数列表={}", validOrderCountList);


        //高级写法--4,统计订单总数  totalOrderCountSum   累加器
        /*totalOrderCountSum = orderCuntList.stream().reduce(0, new BinaryOperator<Integer>() {
            @Override
            public Integer apply(Integer num1, Integer num2) {
                return num1+num2;//累加
            }
        });*/

        /*totalOrderCountSum = orderCuntList.stream().reduce(0, (Integer num1, Integer num2)->{
            return num1+num2;//累加
        });*/


         /*totalOrderCountSum = orderCuntList.stream().reduce(0, (x, y) -> {
            return x + y;
        });*/

        // totalOrderCountSum = orderCuntList.stream().reduce(0, (x, y) -> x + y);  //选中(x, y) -> x + y，按Alt+enter生成Lambda表达式
        // totalOrderCountSum = orderCuntList.stream().reduce(0, Integer::sum);
        // totalOrderCountSum = orderCuntList.stream().reduce(Integer::sum).get();


        //6,计算订单完成率：orderCompletionRate=validOrderCount/totalOrderCount*100%
        Double orderCompletionRate = 0.0;
        if (totalOrderCountSum != 0) {
            orderCompletionRate = 1.0 * validOrderCountSum / totalOrderCountSum;
        }

        //7,封装OrderReportVO对象，并返回
        return OrderReportVO.builder()
                .dateList(StringUtils.join(dateList, ','))
                .orderCountList(StringUtils.join(orderCuntList, ','))
                .validOrderCountList(StringUtils.join(validOrderCountList, ','))
                .validOrderCount(validOrderCountSum)
                .totalOrderCount(totalOrderCountSum)
                .orderCompletionRate(orderCompletionRate)
                .build();
    }


    /**
     * 销量前10统计
     *
     * @param begin
     * @param end
     * @return
     */
    @Override
    public SalesTop10ReportVO top10(LocalDate begin, LocalDate end) {
        //获取当天最大时间＆最小时间
        LocalDateTime beginTime = LocalDateTime.of(begin, LocalTime.MAX);
        LocalDateTime endTime = LocalDateTime.of(end, LocalTime.MIN);

        //查询销量数据
        List<GoodsSalesDTO> goodsSalesDTOS = orderMapper.top10(Orders.COMPLETED, beginTime, endTime);
        //1，构造商品名称列表 nameList
        List<String> nameList = new ArrayList<>();
        nameList = goodsSalesDTOS.stream().map((dto) -> {
            return dto.getName();
        }).collect(Collectors.toList());
        //nameList = goodsSalesDTOS.stream().map(GoodsSalesDTO::getName).collect(Collectors.toList());
        // dto.getName()高亮显示，按Alt+enter转变成这段代码

        //2，构造销量列表 numberList
        List<Integer> numberList = new ArrayList<>();
        numberList = goodsSalesDTOS.stream().map(GoodsSalesDTO::getNumber).collect(Collectors.toList());


        //3,封装SalesTop10ReportVO对象，并返回
        return SalesTop10ReportVO.builder()
                .nameList(StringUtils.join(nameList, ','))
                .numberList(StringUtils.join(numberList, ','))
                .build();
    }

    /**
     * 借助POI导出数据--报表导出
     *
     * @param response
     */
    @Override
    public void export(HttpServletResponse response) {
        //定义需要导出数据的开始时间，结束时间
        LocalDate now = LocalDate.now();
        LocalDateTime begin = LocalDateTime.of(now.minusDays(30), LocalTime.MIN);//2023-11-08 00:00:00
        LocalDateTime end = LocalDateTime.of(now.minusDays(1), LocalTime.MAX);//2023-11-08 00:00:00
        System.out.println(begin);
        System.out.println(end);

        //0,获取概览数据
        BusinessDataVO businessData = workspaceService.getBusinessData(begin, end);



        //,2,基于模板创建工作簿对象
        //src\main\resources\template\运营数据报表模板.xlsx
        InputStream is = this.getClass().getClassLoader().getResourceAsStream("template\\运营数据报表模板.xlsx");
        XSSFWorkbook workbook = null;
        try {
            workbook = new XSSFWorkbook(is);

            //3,获取工作表对象
            XSSFSheet sheet = workbook.getSheetAt(0);

            //4,获取指定的一些行对象，以便获取单元格
            //5,将前面获取到的数据填充到指定的单元格

            String time = "时间：" + now.minusDays(30) + "至" + now.minusDays(1);
            sheet.getRow(1).getCell(1).setCellValue(time);
            sheet.getRow(3).getCell(2).setCellValue(businessData.getTurnover());//营业额
            sheet.getRow(3).getCell(4).setCellValue(businessData.getOrderCompletionRate()); //订单完成率
            sheet.getRow(3).getCell(6).setCellValue(businessData.getNewUsers());//新增用户
            sheet.getRow(4).getCell(2).setCellValue(businessData.getValidOrderCount());//有效订单
            sheet.getRow(4).getCell(4).setCellValue(businessData.getUnitPrice());//评价客单价


            //1，获取近30天定的明细数据,并将数据填充到Excel中
            List<BusinessDataVO> businessDataVOList=new ArrayList<>();
            for (int i = 0; i <30 ; i++) {
              LocalDate date=  now.minusDays(30-i);   //2023-11-08
                begin= LocalDateTime.of(date,LocalTime.MIN);//2023-11-08 00:00:00
                end=LocalDateTime.of(date,LocalTime.MAX);  //2023-11-08 23:59:59
                businessData=  workspaceService.getBusinessData(begin,end);
                XSSFRow row = sheet.getRow(7 + i);
                row.getCell(1).setCellValue(date.toString());
                row.getCell(2).setCellValue(businessData.getTurnover());
                row.getCell(3).setCellValue(businessData.getValidOrderCount());
                row.getCell(4).setCellValue(businessData.getOrderCompletionRate());
                row.getCell(5).setCellValue(businessData.getUnitPrice());
                row.getCell(6).setCellValue(businessData.getNewUsers());
            }



            //6,将内存中的文件以文件流的方式下载到客户端浏览器
            ServletOutputStream outputStream = response.getOutputStream();
            workbook.write(outputStream);

            //7,关闭资源
            outputStream.close();
            workbook.close();
            is.close();

        } catch (IOException e) {
            e.printStackTrace();
        }
    }


    /**
     * 获取日期列表数据
     *
     * @param begin
     * @param end
     * @return
     */
    private List<LocalDate> getDateList(LocalDate begin, LocalDate end) {
        //构造日期列表数据，dateList  例如：2022-10-01,2022-10-02,2022-10-03
        List<LocalDate> dateList = new ArrayList<>();
        dateList.add(begin);
        //使用while循环，往dateList添加日期
        while (!begin.equals(end)) {
            begin = begin.plusDays(1);  //12-01,12-02...12-05,12-06
            dateList.add(begin);
        }
        log.info("dateList:{}", dateList);
        return dateList;
    }
}
